{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# KNN(k-近邻算法)\n",
    "from sklearn.neighbors import KNeighborsClassifier # 导入KNN分类器\n",
    "from sklearn.datasets import make_moons # 导入月亮数据集生成函数，这个数据集有两个特征，形状像两个月亮,适合用于分类\n",
    "from sklearn.model_selection import train_test_split # 导入数据集划分函数\n",
    "from sklearn.metrics import accuracy_score # 导入准确率计算函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9333333333333333"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X, y = make_moons(noise=0.3) # 生成带有噪声的月亮数据集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 划分训练集和测试集,第一个参数是特征数据，第二个参数是目标标签，test_size=0.3表示30%的数据用于测试集，其余70%用于训练集\n",
    "model = KNeighborsClassifier() # 创建KNN模型\n",
    "model.fit(X_train, y_train) # 训练模型\n",
    "y_pred = model.predict(X_test) # 预测测试集\n",
    "accuracy = accuracy_score(y_test, y_pred) # 计算准确率\n",
    "accuracy # 输出准确率"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
